package org.jsola.contract.service.impl;

import org.jsola.contract.common.ExampleKit;
import org.jsola.contract.constant.ContractConstants;
import org.jsola.contract.dao.IPersonSignatureDAO;
import org.jsola.contract.dto.PersonSignatureAddDTO;
import org.jsola.contract.dto.PersonSignatureUpdateDTO;
import org.jsola.contract.entity.AppendixDO;
import org.jsola.contract.entity.PersonSignatureDO;
import org.jsola.contract.query.PersonSignatureQuery;
import org.jsola.contract.service.IPersonSignatureService;
import org.jsola.contract.vo.PersonSignatureListVO;
import org.jsola.contract.vo.PersonSignatureVO;
import org.jsola.core.Page;
import org.jsola.user.core.TokenUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 合同个人签名表
 *
 * @author JanusMix
 */
@Service("contractPersonSignatureServiceImpl")
public class PersonSignatureServiceImpl implements IPersonSignatureService {

    @Autowired
    private IPersonSignatureDAO personSignatureDAO;

    @Override
    @Transactional(value = ContractConstants.TX, rollbackFor = Exception.class)
    public PersonSignatureVO save(PersonSignatureAddDTO personSignatureAddDTO, TokenUser tokenUser) {
        // 转DO
        PersonSignatureDO personSignatureDO = personSignatureAddDTO.to(PersonSignatureDO.class);
        // 保存
        personSignatureDO = save(personSignatureDO, tokenUser.getSiteId(), tokenUser.getUserId());
        return personSignatureDO.to(PersonSignatureVO.class);
    }

    @Override
    @Transactional(value = ContractConstants.TX, rollbackFor = Exception.class)
    public int update(PersonSignatureUpdateDTO personSignatureUpdateDTO, TokenUser tokenUser) {
        //转DO
        PersonSignatureDO personSignatureDO = personSignatureUpdateDTO.to(PersonSignatureDO.class);
        //根据主键更新，只更新非null值
        return updateByIdSelective(personSignatureDO, tokenUser.getSiteId(), tokenUser.getUserId());
    }

    @Override
    @Transactional(value = ContractConstants.TX, rollbackFor = Exception.class)
    public int deleteByIds(TokenUser tokenUser, Long... personSignatureIds) {
        return deleteByIds(tokenUser.getSiteId(), tokenUser.getUserId(), (Object[]) personSignatureIds);
    }


    @Override
    public PersonSignatureVO selectById(Long personSignatureId, String siteId) {
        PersonSignatureDO personSignatureDO = selectDOById(personSignatureId, siteId);
        if (personSignatureDO == null) {
            return null;
        }
        return personSignatureDO.to(PersonSignatureVO.class);
    }

    @Override
    public List<PersonSignatureListVO> select(PersonSignatureQuery personSignatureQuery, String siteId) {
        List<PersonSignatureDO> personSignatureDOList = selectDO(personSignatureQuery, siteId);
        if(CollectionUtils.isEmpty(personSignatureDOList)) {
            return personSignatureDOList == null ? null : new ArrayList<>();
        }
        return personSignatureDOList.stream()
                .map(personSignatureDO -> personSignatureDO.to(PersonSignatureListVO.class))
                .collect(Collectors.toList());
    }

    @Override
    public int selectCount(PersonSignatureQuery personSignatureQuery, String siteId) {
        Example example = buildExample(personSignatureQuery,siteId);
        return personSignatureDAO.selectCountByExample(example);
    }

    @Override
    public Page<PersonSignatureListVO> selectPage(PersonSignatureQuery personSignatureQuery, String siteId) {
        Example example = buildExample(personSignatureQuery,siteId);
        Page<PersonSignatureDO> page = personSignatureDAO.selectPageByExample(example,
                personSignatureQuery.getPageNo(),
                personSignatureQuery.getPageSize());

        return page.to(PersonSignatureListVO.class);
    }

    @Override
    public PersonSignatureDO selectDOById(Long personSignatureId, String siteId) {
        return listById(personSignatureId, siteId);
    }

    @Override
    public List<PersonSignatureDO> selectDO(PersonSignatureQuery personSignatureQuery, String siteId) {
        Example example = buildExample(personSignatureQuery,siteId);
        return personSignatureDAO.selectByExample(example);
    }

    @Override
    @Transactional(value = ContractConstants.TX, rollbackFor = Exception.class)
    public void pubshPersonSignature(Long contractId, String sealString, TokenUser tokenUser) {
        PersonSignatureDO personSignature = findByContractId(contractId, tokenUser.getSiteId());
        if (Objects.isNull(personSignature)) {
            // 新增
            PersonSignatureAddDTO addDTO = new PersonSignatureAddDTO();
            addDTO.setContractId(contractId);
            addDTO.setSeal(sealString);
            addDTO.setUserId(tokenUser.getUserId());

            save(addDTO, tokenUser);
        } else {
            // 修改
            PersonSignatureUpdateDTO updateDTO = new PersonSignatureUpdateDTO();
            updateDTO.setId(personSignature.getId());
            updateDTO.setSeal(sealString);
            updateDTO.setUserId(tokenUser.getUserId());

            update(updateDTO, tokenUser);
        }
    }

    @Override
    public PersonSignatureDO findByContractId(Long contractId, String siteId) {
        Example example = new Example(PersonSignatureDO.class);
        example.and()
                .andEqualTo("contractId", contractId)
                .andEqualTo("siteId", siteId);
        return personSignatureDAO.selectOneByExample(example);
    }

    @Override
    @Transactional(value = ContractConstants.TX, rollbackFor = Exception.class)
    public void deleteByContractId(Long contractId, TokenUser tokenUser) {
        Example example = new Example(PersonSignatureDO.class);
        example.and()
                .andEqualTo("contractId", contractId)
                .andEqualTo("siteId", tokenUser.getSiteId());
        personSignatureDAO.deleteByExample(example);
    }

    @Override
    public void deleteByContractIds(List<Long> contractIds, TokenUser tokenUser) {
        if (CollectionUtils.isEmpty(contractIds)) {
            return;
        }
        Example example = new Example(PersonSignatureDO.class);
        example.and()
                .andIn("contractId", contractIds)
                .andEqualTo("siteId", tokenUser.getSiteId());
        personSignatureDAO.deleteByExample(example);
    }


    /**
     * 根据查询参数，构建example

     * @param personSignatureQuery 查询参数
     * @param siteId 所属站点id
     * @return example
     */
    private Example buildExample(PersonSignatureQuery personSignatureQuery, String siteId) {
        Example example = new Example(PersonSignatureDO.class);
        example.and()
                .andEqualTo("siteId", siteId);
        if (personSignatureQuery.getContractId() != null) {
            example.and().andEqualTo("contractId", personSignatureQuery.getContractId());
        }
        if (personSignatureQuery.getSeal() != null) {
            example.and().andEqualTo("seal", personSignatureQuery.getSeal());
        }
        if (personSignatureQuery.getUserId() != null) {
            example.and().andEqualTo("userId", personSignatureQuery.getUserId());
        }
        // 排序
        ExampleKit.setExampleOrder(example,personSignatureQuery.getOrders());
        return example;
    }
}




